package astudy.networking.tcp;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class CommandClient {

	public static void main(String[] argv) {
		
		try {
			String serverAddr = "127.0.0.1";
			int serverPort = 9999;
			Socket client = new Socket(serverAddr, serverPort);

			BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
			PrintWriter os = new PrintWriter(client.getOutputStream());
			
			String cmdLine = null;
			BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));
			while ((cmdLine = cmdIn.readLine()) != null) {
				String[] tmp = cmdLine.trim().split("\\s+");
				if (tmp.length == 0) {
					//do nothing
				} else {
					String cmd = tmp[0];
					String[] args = new String[tmp.length-1];
					System.arraycopy(tmp, 1, args, 0, args.length);

					os.println(cmdLine);
					os.flush();
					//print result
					String line = is.readLine();
					if ("get".equalsIgnoreCase(cmd)) {
						int port = Integer.valueOf(line);
						System.out.println(line);
						get(serverAddr, port, args);
					} else {
						if (line != null) {
							System.out.println(line.replace("\\n", "\n"));
							if ("quit".equalsIgnoreCase(line)) {
								break;
							}
						}
					}
				}
			}
			is.close();
			os.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void get(String addr, int port, String[] args) {
		
		if (args.length < 2) {
			throw new RuntimeException("You should specified file names.");
		} else {
			String path = args[1];
			File file = new File("D:/", path);
			if (file.exists()) {
				throw new RuntimeException(path + " exists!");
			} else {
				FileReceiver fileReceiver = new FileReceiver(addr, port);
				fileReceiver.save(file);
			}
		}
	}
}
